PEP 723 – Inline script metadata
implemented in a couple of tools, ideally including pip-run and pipx. This PEP specifies a metadata format that can be embedded in single-file Python scripts to assist launchers, IDEs and other external tools which may need to interact with such scripts. (Abstract)
「単一ファイルのPythonスクリプトに埋め込めるメタデータの形式を指定する」
「メタデータはランチャー、IDE、他の外部ツールを助ける」
Python is routinely used as a scripting language, with Python scripts as a (better) alternative to shell scripts, batch files, etc. (Motivation)
IMO:スクリプト1ファイルのユースケースをもっと便利にしようという意図(ファイルをいくつも置いたプロジェクトまではいかない)
it is usually stored as a single file and does not expect the availability of any other local code that may be used for imports.
そういうもの(スクリプトは自身がimportするコードの入手可能性は期待しない)として、Pythonスクリプトだけが共有されてきた
スクリプトユーザの課題:スクリプトを実行するツール向けのメタデータを定義する標準的な機構がない
For example, a tool that runs a script may need to know which dependencies are required or the supported version(s) of Python.
By defining a standard format for storing such metadata, existing tools, as well as any future tools, will be able to obtain that information without requiring users to include tool-specific metadata in their scripts.
This PEP defines a mechanism for embedding metadata within the script itself, and not in an external file. (Rationale)
pyproject.tomlのようなデータ形式で
このPEPがサポートするユースケース
If we take Hatch as an example, the interface would be simply hatch run /path/to/script.py [args] and Hatch will manage the environment for that script.
シバンも書ける
A script that desires to transition to a directory-type project
「スクリプトからプロジェクトにしやすい」
Users that wish to avoid manual dependency management.
Specification
This PEP defines a metadata comment block format loosely inspired [2] by reStructuredText Directives.
[2] The syntax is taken directly from the final resolution of the Blocks extension to Python Markdown.
コメントブロックの開始:# /// TYPE
TYPE determines how to process the content.
ブロックの終了:# ///
Every line between these two lines (# /// TYPE and # ///) MUST be a comment starting with #.
This is the canonical regular expression that MAY be used to parse the metadata:
code:inline script metadataの正規表現.py
(?m)^# /// (?P<type>a-zA-Z0-9-+)$\s(?P<content>(^#(| .*)$\s)+)^# ///$ script type
The first type of metadata block is named script which contains script metadata (dependency data and tool configuration).
This document MAY include top-level fields dependencies and requires-python, and MAY optionally include a [tool] table.
It has the same semantics as the tool table in pyproject.toml.
top-level fields
dependencies
requires-python
Reference Implementation
metadataのread
正規表現
metadataのmodify
How to Teach This
# /// scriptで始まるコメント
# ///まで
2つを指定できる
dependencies
A list of strings that specifies the runtime dependencies of the script
requires-python
In addition, a [tool] table is allowed.
「(pyproject.tomlにあるような)[tool]テーブル(ツールごとの設定を書ける)も許可されている」
Tooling buy-in
Pantsbuild and Pex
Mypy and Ruff
Hatch